<template>
	<view class="order-management">
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<picker 
				:range="statusOptions" 
				range-key="name"
				:value="statusIndex"
				@change="onStatusChange"
			>
				<view class="filter-item">
					<text>{{ statusOptions[statusIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
			
			<picker 
				:range="categoryOptions" 
				range-key="name"
				:value="categoryIndex"
				@change="onCategoryChange"
			>
				<view class="filter-item">
					<text>{{ categoryOptions[categoryIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			class="order-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="order-item" v-for="order in orderList" :key="order.id" @click="goOrderDetail(order.id)">
				<view class="order-header">
					<text class="order-title">{{ order.title }}</text>
					<text class="order-status" :class="getStatusClass(order.status)">
						{{ getStatusText(order.status) }}
					</text>
				</view>
				
				<view class="order-content">
					<text class="order-desc">{{ order.description }}</text>
				</view>
				
				<view class="order-info">
					<view class="info-row">
						<text class="label">预算：</text>
						<text class="value budget">￥{{ order.budget }}</text>
					</view>
					<view class="info-row">
						<text class="label">分类：</text>
						<text class="value">{{ order.categoryName }}</text>
					</view>
					<view class="info-row">
						<text class="label">发布者：</text>
						<text class="value">{{ order.userName }}</text>
					</view>
					<view class="info-row" v-if="order.techName">
						<text class="label">技术员：</text>
						<text class="value">{{ order.techName }}</text>
					</view>
					<view class="info-row">
						<text class="label">创建时间：</text>
						<text class="value">{{ formatTime(order.createTime) }}</text>
					</view>
				</view>
				
				<!-- 管理员操作 -->
				<view class="admin-actions">
					<button 
						class="action-btn assign" 
						v-if="order.status === 1"
						@click.stop="assignOrder(order.id)"
					>
						指派技术员
					</button>
					
					<button 
						class="action-btn cancel" 
						v-if="order.status <= 2"
						@click.stop="cancelOrder(order.id)"
					>
						强制取消
					</button>
				</view>
			</view>
			
			<view class="load-more" v-if="hasMore">
				<text v-if="loading">加载中...</text>
				<text v-else>上拉加载更多</text>
			</view>
			
			<view class="no-more" v-if="!hasMore && orderList.length > 0">
				<text>没有更多数据了</text>
			</view>
			
			<view class="empty" v-if="!loading && orderList.length === 0">
				<text>暂无订单数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				pageNum: 1,
				pageSize: 10,
				statusIndex: 0,
				categoryIndex: 0,
				statusOptions: [
					{ name: '全部状态', value: '' },
					{ name: '待接单', value: 1 },
					{ name: '进行中', value: 2 },
					{ name: '待验收', value: 3 },
					{ name: '已完成', value: 4 },
					{ name: '已取消', value: 5 }
				],
				categoryOptions: [
					{ name: '全部分类', value: '' }
				]
			}
		},
		onLoad() {
			this.checkPermission()
			this.loadCategories()
			this.loadOrders()
		},
		methods: {
			checkPermission() {
				if (!this.$store.getters.isAdmin) {
					uni.showToast({
						title: '权限不足',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			},
			
			async loadCategories() {
				try {
					const res = await this.$api.getCategoryList()
					if (res.code === 200) {
						const categories = res.data.map(item => ({
							name: item.name,
							value: item.id
						}))
						this.categoryOptions = [{ name: '全部分类', value: '' }, ...categories]
					}
				} catch (error) {
					console.error('加载分类失败:', error)
				}
			},
			
			async loadOrders(refresh = false) {
				if (this.loading) return
				
				this.loading = true
				
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}
				
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}
					
					if (this.statusOptions[this.statusIndex].value) {
						params.status = this.statusOptions[this.statusIndex].value
					}
					
					if (this.categoryOptions[this.categoryIndex].value) {
						params.categoryId = this.categoryOptions[this.categoryIndex].value
					}
					
					const res = await this.$api.getOrderList(params)
					
					if (res.code === 200) {
						const newOrders = res.data || []
						
						if (refresh) {
							this.orderList = newOrders
						} else {
							this.orderList = [...this.orderList, ...newOrders]
						}
						
						this.hasMore = newOrders.length === this.pageSize
						this.pageNum++
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.refreshing = false
				}
			},
			
			onRefresh() {
				this.refreshing = true
				this.loadOrders(true)
			},
			
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadOrders()
				}
			},
			
			onStatusChange(e) {
				this.statusIndex = e.detail.value
				this.loadOrders(true)
			},
			
			onCategoryChange(e) {
				this.categoryIndex = e.detail.value
				this.loadOrders(true)
			},
			
			goOrderDetail(id) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},
			
			assignOrder(id) {
				uni.navigateTo({
					url: `/pages/dispatcher/assign?orderId=${id}`
				})
			},
			
			async cancelOrder(id) {
				uni.showModal({
					title: '确认取消',
					content: '确定要强制取消此订单吗？此操作不可撤销。',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.cancelOrder(id)
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								})
								this.loadOrders(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '取消失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			getStatusClass(status) {
				const statusMap = {
					1: 'status-pending',
					2: 'status-processing',
					3: 'status-reviewing',
					4: 'status-completed',
					5: 'status-cancelled'
				}
				return statusMap[status] || ''
			},
			
			getStatusText(status) {
				const statusMap = {
					1: '待接单',
					2: '进行中',
					3: '待验收',
					4: '已完成',
					5: '已取消'
				}
				return statusMap[status] || '未知'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-management {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f5f5;
	}
	
	.filter-bar {
		background: #fff;
		padding: 20rpx;
		display: flex;
		gap: 20rpx;
		border-bottom: 1rpx solid #eee;
		flex-wrap: wrap;
		
		.filter-item {
			flex: 1;
			min-width: 200rpx;
			max-width: calc(50% - 10rpx);
		}
		
		@media (max-width: 750rpx) {
			.filter-item {
				min-width: 100%;
				max-width: 100%;
			}
		}
		
		.filter-item {
			flex: 1;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			
			.arrow {
				color: #999;
				font-size: 20rpx;
			}
		}
	}
	
	.order-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	.order-item {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 20rpx;
			
			.order-title {
				flex: 1;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-right: 20rpx;
				line-height: 1.4;
			}
			
			.order-status {
				font-size: 24rpx;
				padding: 6rpx 16rpx;
				border-radius: 15rpx;
				white-space: nowrap;
			}
		}
		
		.order-content {
			margin-bottom: 20rpx;
			
			.order-desc {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}
		
		.order-info {
			margin-bottom: 20rpx;
			
			.info-row {
				display: flex;
				margin-bottom: 10rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					font-size: 24rpx;
					color: #666;
					width: 120rpx;
				}
				
				.value {
					flex: 1;
					font-size: 24rpx;
					color: #333;
					
					&.budget {
						font-weight: bold;
						color: #FF6B6B;
					}
				}
			}
		}
		
		.admin-actions {
			display: flex;
			gap: 20rpx;
			
			.action-btn {
				flex: 1;
				height: 60rpx;
				border: none;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.assign {
					background: #007bff;
					color: #fff;
				}
				
				&.cancel {
					background: #dc3545;
					color: #fff;
				}
			}
		}
	}
	
	.load-more, .no-more {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.status-pending {
		background: #fff3cd;
		color: #856404;
	}
	
	.status-processing {
		background: #d1ecf1;
		color: #0c5460;
	}
	
	.status-reviewing {
		background: #ffeaa7;
		color: #e17055;
	}
	
	.status-completed {
		background: #d4edda;
		color: #155724;
	}
	
	.status-cancelled {
		background: #f8d7da;
		color: #721c24;
	}
</style>